<template>
  <div class="afterInvestDel-page">
    <pubChunk :mt="20">
      <span slot="title">收益风险指标</span>
      <div
        v-show="navActive == 1"
        :key="list_riskIndicators_key1"
        class="showChunk"
      >
        <el-table
          v-loading="listLoading_riskIndicators"
          :data="list_riskIndicators"
          fit
          default-expand-all
          row-key="rowKey"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          size="mini"
          style="width: 100%"
          :cell-class-name="cellClass"
          :cell-style="{ padding: '8px 0' }"
          :header-cell-style="{ color: '#333' }"
        >
          <el-table-column
            prop="name"
            label="名称"
            fixed="left"
            :width="flexColumnWidth('名称', 'name', list_riskIndicators)"
          >
            <template slot-scope="{ row }">
              <!-- <div :title="row.name"> -->
              <span
                :title="row.name"
                v-if="row.classifyId"
                style="cursor: pointer; color: #1890ff"
                @click.stop="groupDeltailHandle(row.classifyId)"
              >
                {{ row.name }}
              </span>
              <span
                v-else
                :title="row.name"
                style="cursor: pointer; color: #666"
              >
                {{ row.name }}
              </span>
              <!-- </div> -->
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="nominalAmount"
            label="名义金额(万元)"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.nominalAmount">{{ row.nominalAmount }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column> -->
          <el-table-column
            prop="initMoney"
            label="资产金额（万元）"
            align="center"
            min-width="120"
          >
            <template slot-scope="{ row }">
              <span v-if="row.initMoney">{{ row.initMoney }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="" label="权重" align="center">
            <template slot-scope="{ row }">
              <span v-if="row.initMoney">{{ ((row.initMoney / list_riskIndicators[0].initMoney) * 100) | toFixed2 }}%</span>
              <span v-else>--</span>
            </template>
          </el-table-column> -->
          <!-- <el-table-column prop="weight" label="权重" align="center">
            <template slot-scope="{ row }">
              <span v-if="row.weight">{{ row.weight | toFixed2 }}%</span>
              <span v-else>--</span>
            </template>
          </el-table-column> -->
          <el-table-column
            prop="incomeRate"
            label="收益率"
            min-width="100"
            align="center"
          >
            <template slot-scope="{ row }">
              <span
                v-if="row.incomeRate"
                :class="row.incomeRate >= 0 ? 'positiveFc' : 'negativeFc'"
              >
                {{ row.incomeRate }}%
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="annualizedIncomeRate"
            label="年化收益率"
            align="center"
          >
            <template slot-scope="scope">
              <span
                v-if="scope.row.annualizedIncomeRate"
                :class="
                  scope.row.annualizedIncomeRate >= 0
                    ? 'positiveFc'
                    : 'negativeFc'
                "
              >
                {{ scope.row.annualizedIncomeRate }}%
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="annualFluctuationsRate"
            label="年化波动率"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="sharpeRate"
            label="夏普比率"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="maximumDrawdownRate"
            label="最大回撤"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="calmarRate"
            label="卡玛比率"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="maxBackIncomDay"
            label="最大回撤回补期"
            min-width="100"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.maxBackIncomDay">{{ row.maxBackIncomDay }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="maxNotByNewHightDay"
            label="最大不创新高天数"
            min-width="100"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.maxNotByNewHightDay">
                {{ row.maxNotByNewHightDay }}
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="investWinningRate"
            label="投资胜率"
            align="center"
          ></el-table-column>
        </el-table>
      </div>
      <div
        v-show="navActive == 2"
        :key="list_riskIndicators_key2"
        class="showChunk"
      >
        <!-- class="expand-table__hover-bg riskIndicators-table" -->
        <el-table
          v-loading="listLoading_riskIndicators"
          :data="list_riskIndicators"
          fit
          default-expand-all
          row-key="rowKey"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          size="mini"
          style="width: 100%"
          :cell-style="{ padding: '8px 0' }"
          :header-cell-style="{ color: '#333' }"
        >
          <el-table-column
            prop="name"
            label="名称"
            min-width="120"
            show-overflow-tooltip
          >
            <template slot-scope="{ row }">
              <span
                v-if="row.strategyId"
                style="cursor: pointer; color: #1890ff"
                @click.stop="strategyDeltailHandle(row.strategyId)"
              >
                {{ row.name }}
              </span>
              <span
                v-else-if="row.classifyId"
                style="cursor: pointer; color: #1890ff"
                @click.stop="groupDeltailHandle(row.classifyId)"
              >
                {{ row.name }}
              </span>
              <span v-else style="color: #666">{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="initMoney"
            label="资产金额（万元）"
            align="center"
            min-width="120"
          >
            <template slot-scope="{ row }">
              <span v-if="row.initMoney">{{ row.initMoney }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="initialShare"
            label="资产份额"
            min-width="100"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.initialShare">{{ row.initialShare }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="netWorthTime"
            label="净值时间"
            min-width="100"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.netWorthTime">{{ row.netWorthTime }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="networthValue"
            label="最新净值"
            min-width="100"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.networthValue">{{ row.networthValue }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="incomeRate"
            label="收益率"
            min-width="100"
            align="center"
          >
            <template slot-scope="{ row }">
              <span
                v-if="row.incomeRate"
                :class="row.incomeRate >= 0 ? 'positiveFc' : 'negativeFc'"
              >
                {{ row.incomeRate }}%
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="annualizedIncomeRate"
            label="年化收益率"
            align="center"
          >
            <template slot-scope="scope">
              <span
                v-if="scope.row.annualizedIncomeRate"
                :class="
                  scope.row.annualizedIncomeRate >= 0
                    ? 'positiveFc'
                    : 'negativeFc'
                "
              >
                {{ scope.row.annualizedIncomeRate }}%
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="annualFluctuationsRate"
            label="年化波动率"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="sharpeRate"
            label="夏普比率"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="maximumDrawdownRate"
            label="最大回撤"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="calmarRate"
            label="卡玛比率"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="maxBackIncomDay"
            label="最大回撤回补期"
            min-width="100"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.maxBackIncomDay">{{ row.maxBackIncomDay }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="maxNotByNewHightDay"
            label="最大不创新高天数"
            min-width="100"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.maxNotByNewHightDay">
                {{ row.maxNotByNewHightDay }}
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="investWinningRate"
            label="投资胜率"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="investStartTime"
            label="开始时间"
            min-width="100"
            align="center"
          >
            <template slot-scope="{ row }">
              <span v-if="row.investStartTime">{{ row.investStartTime }}</span>
              <span v-else>--</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </pubChunk>
  </div>
</template>
<script>
import pubChunk from "@/components/investComn/pubChunk.vue";
import {
  riskIndicators,
  getIndexRiskByIndexTypeAndTime,
} from "@/api/policyManage";
import {
  getRiskRateById,
  findClassifyByCompositionId,
  findCompositionClassifyStrategyByCompositionId,
} from "@/api/combManage";
import mixin from "./mixins";
import { getMaxLength } from "@/utils/pro";

export default {
  mixins: [mixin],
  components: { pubChunk },
  data() {
    return {
      list_riskIndicators_key: 0,
      list_riskIndicators_key1: 1,
      list_riskIndicators: [], // 收益风险指标
      tip_list_riskIndicators: 1,
      params: {
        compositionId: "",
      },
      _list_riskIndicators: [], // 保存基础 收益风险指标
      list_riskIndicators_key2: 100,
      nominalAmount: "",
      strategy_dels: {},
      combTree: [],
      chart_date: [],
      combTreeStrategyList: [],
      listLoading_riskIndicators1: false,
      listLoading_riskIndicators4: false,
      listLoading_riskIndicators: false,
    };
  },
  props: {
    navActive: {
      type: String | Number,
    },
    chart1List: {
      type: Object | Array,
    },
    contrastOptions_obj_parent: {
      type: Array | Object,
    },
    chart_date_parent: {
      type: Array | Object,
    },
    indexTypes: {
      type: String | Number,
      default: "",
    },
    titleDataType: {
      type: String | Number,
      default: 0,
    },
  },
  created() {},
  mounted() {},
  watch: {
    chart_date_parent: {
      handler(newVal, oldVal) {
        this.chart_date = newVal;
      },
      deep: true,
    },
    navActive: {
      handler(newVal, oldVal) {
        if (newVal == 1) {
          this.sublistHandle();
        } else {
          this.strategySublistHandle1();
        }
      },
    },
    indexTypes: {
      handler(newVal, oldVal) {
        if (this.params.compositionId) {
          if (oldVal && this.list_riskIndicators.length) {
            this.getIndexRiskByIndexTypeAndTime(newVal);
          }
        } else {
          this.getriskIndicators(); // 风险指标
        }
      },
      deep: true,
    },
    chart1List: {
      handler(newVal, oldVal) {
        if (this.list_riskIndicators.length) {
          this.list_riskIndicators = this.riskRecursionHandle(
            newVal,
            this.list_riskIndicators
          );
          this.list_riskIndicators[0].nominalAmount = this.nominalAmount;
          if (this.navActive == 1) {
            this.list_riskIndicators_key1++;
          }
          if (this.navActive == 2) {
            this.list_riskIndicators_key2++;
          }
        }
      },
      deep: true,
    },
  },
  methods: {
    init(strategy_dels) {
      this.strategy_dels = strategy_dels;
      this.params.compositionId =
        strategy_dels.riskIndicatorsBean.compositionId;
      if (this.params.compositionId) {
        this.findCompositionClassifyStrategyByCompositionId();
        this.getRiskRateByIdHandle();
      } else {
        this.getriskIndicators(); // 风险指标
      }
    },
    //  风险指标
    getriskIndicators() {
      riskIndicators({
        strategyId: this.strategyId,
      }).then((res) => {
        // console.log('风险指标', res)
        this.list_riskIndicators.push(res.body);
        this.list_riskIndicators[0].name = this.strategy_dels.strategyName;
        this.getIndexRiskByIndexTypeAndTime(this.indexTypes);
      });
    },
    // 收益风险指标
    getRiskRateByIdHandle() {
      this.listLoading_riskIndicators1 = true;
      getRiskRateById({
        ...this.params,
        strategyId: this.strategyId,
        showStrategyRisk: true,
        userId: this.userId,
      }).then((res) => {
        // console.log('收益风险指标', res)
        this.listLoading_riskIndicators1 = false;
        let _list_riskIndicators = [];
        _list_riskIndicators = res.body;
        _list_riskIndicators[0].name = this.strategy_dels.strategyName;
        _list_riskIndicators[0].strategyId = null; // 后端给组合传回了strategyId
        _list_riskIndicators[0].rowKey = 1;
        _list_riskIndicators[0].classifyNetWorthExtendBeans =
          res.body[0].compositionNetWorthExtendBeans;
        this.list_riskIndicators = _list_riskIndicators;

        if (this.chart1List.length) {
          this.list_riskIndicators = this.riskRecursionHandle(
            this.chart1List,
            this.list_riskIndicators
          );
        }
        if (this.navActive == 1) {
          this.sublistHandle();
        } else {
          this.strategySublistHandle1();
        }
        this.getIndexRiskByIndexTypeAndTime(this.indexs);
      });
    },
    // 收益风险指标 指数
    getIndexRiskByIndexTypeAndTime(indexType) {
      getIndexRiskByIndexTypeAndTime({
        indexType,
        startTime: this.chart_date[0],
        endTime: this.chart_date[1],
      }).then((res) => {
        // console.log('风险指标 指数', res)
        this.list_riskIndicators = [this.list_riskIndicators[0]];

        Object.keys(res.body).forEach((index) => {
          const name = this.contrastOptions_obj_parent[index];
          this.list_riskIndicators.push({
            name,
            rowKey: index + 10000,
            classifyNetWorthExtendBeans: res.body[index].scopeIndexVos,
            ...res.body[index],
          });
          this.list_riskIndicators = this.riskRecursionHandle(
            this.chart1List,
            this.list_riskIndicators
          );
        });
      });
    },
    riskRecursionHandle(resList, list) {
      list.map((items, i) => {
        const resList_i = resList.findIndex((item) => item.name == items.name);
        if (resList_i != -1) {
          const res = resList[resList_i];
          list[i] = {
            strategyId: items.strategyId,
            classifyId: items.classifyId,
            children: items.children,
            rowKey: items.rowKey,
            weight: items.weight,
            initMoney: items.initMoney,
            nominalAmount: items.nominalAmount,
            initialShare: items.initialShare,
            investStartTime: items.investStartTime,
            netWorthTime: items.netWorthTime,
            networthValue: items.networthValue,
            ...res,
          };
        } else if (items.children) {
          // 分类
          items.children.forEach((_) => {
            list[i] = {
              classifyId: items.classifyId,
              annualFluctuationsRate: "--",
              sharpeRate: "--",
              maxBackIncomDay: "--",
              maximumDrawdownRate: "--",
              calmarRate: "--",
              investWinningRate: "--",
              ...list[i],
            };
          });
        }
        if (items.children) {
          this.riskRecursionHandle(resList, items.children);
        }
      });
      return list;
    },
    sublistHandle() {
      this.listLoading_riskIndicators2 = true;
      findClassifyByCompositionId({
        ...this.params,
      }).then((res) => {
        // console.log('分类列表', res)
        this.listLoading_riskIndicators2 = false;
        this.listLoading = false;
        if (res.body.length > 1) {
          res.body.map((item, i) => {
            item.rowKey = i + 2;
            item.name = item.classfyName;
            item.weight = item.compositionWeight;
            item = Object.assign(item, item.riskIndicatorsBean);
          });
          this.classfyList = res.body;
          this.$set(this.list_riskIndicators[0], "children", res.body);
        } else {
          this.$set(this.list_riskIndicators[0], "children", undefined);
        }
      });
    },
    strategySublistHandle1() {
      this.listLoading_riskIndicators4 = true;
      const children = JSON.parse(JSON.stringify(this.combTree));
      children.forEach((item) => {
        item.children = item.classifyStrategyExt;
        item.rowKey = "F" + item.classifyId;
        item.name = item.classfyName;
        item.hasNetWorth = true;
        item.children.forEach((el) => {
          el.rowKey = "C" + el.strategyId;
          el.name = el.strategyName;
          el.initMoney = el.initialMoney;
          el.hasNetWorth = true;
        });
      });
      this.listLoading_riskIndicators4 = false;
      this.$set(this.list_riskIndicators[0], "children", children);
      // console.log('分类列表1', this.list_riskIndicators)
    },
    strategyDeltailHandle(id) {
      this.$router.push({
        path: `/afterManage/subInvest/details/${id}`,
        query: {
          userId: this.userId,
        },
      });
    },
    groupDeltailHandle(id) {
      console.log(id);
      this.$router.push({
        path: `/afterManage/subInvestClassify/details/${id}`,
      });
    },
    // 组合-分类-策略树形结构
    findCompositionClassifyStrategyByCompositionId() {
      findCompositionClassifyStrategyByCompositionId({
        ...this.params,
      }).then((res) => {
        this.nominalAmount = res.body.strategyCompositionVo.nominalAmount;
        this.combTree = res.body.strategyClassifyVos;
        let list = [];
        this.combTree.forEach((item) => {
          list = list.concat(item.classifyStrategyExt);
        });
        this.combTreeStrategyList = list;
        this.$emit("update:combTreeArr", this.combTree);
        this.$emit("update:combTreeStrategyListArr", list);
        // console.log('组合-分类-策略树形结构', this.combTree)

        if (this.navActive == 2) this.strategySublistHandle1();
      });
    },
    /**
     * 表格数据单行显示内边距为0
     */
    cellClass(row) {
      if (
        (!row.column.label || row.column.label === "名称") &&
        this.maxNameWidth < 400
      ) {
        return "cell-pad-0 nowrap";
      } else if (this.maxNameWidth >= 400) {
        return "cell-pad-0 clamp2Ellipsis";
      }
      return "";
    },
    /**
     * table column 自适应列宽
     * @param label 表名
     * @param prop 表格数据
     * @param tableData 表格数据
     */
    flexColumnWidth(label, prop, tableData) {
      const arr = tableData.map((x) => x[prop]);
      arr.push(label);
      if (getMaxLength(arr) + 80 >= 400) {
        this.maxNameWidth = 400;
      } else {
        this.maxNameWidth = getMaxLength(arr) + 80;
      }
      return this.maxNameWidth;
    },
  },
};
</script>
<style lang="scss" scoped>
.afterInvestDel-page {
  .title {
    font-size: 26px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #262626;
  }
}
</style>
